<template>
  <div>
    <el-card style="margin: 20px 0px">
      <CategorySelect @getCategoryId="getCategoryId" :show="!isShowTable" />
    </el-card>
    <el-card>
      <div v-show="isShowTable">
        <el-button
          type="primary"
          icon="el-icon-plus"
          :disabled="!category3Id"
          @click="addAttr"
          >添加属性</el-button
        >
        <!-- 表格，展示品台属性 -->
        <el-table style="width: 100%" border :data="attrList">
          <el-table-column type="index" label="序号" width="80" align="center">
          </el-table-column>
          <el-table-column prop="attrName" label="属性名称" width="150">
          </el-table-column>
          <el-table-column prop="prop" label="属性值列表" width="width">
            <template slot-scope="{ row }">
              <el-tag
                type="success"
                v-for="attrValue in row.attrValueList"
                :key="attrValue.id"
                style="margin: 0px 20px"
              >
                {{ attrValue.valueName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="prop" label="操作" width="150">
            <template slot-scope="{ row }">
              <el-button
                type="warning"
                icon="el-icon-edit"
                size="mini"
                @click="updateAttr(row)"
              >
              </el-button>
              <el-button type="danger" icon="el-icon-delete" size="mini">
              </el-button>
              <!-- <el-popconfirm title="这是一段内容确定删除吗？">
                <el-button 
                  type="danger" 
                  icon="el-icon-delete" 
                  size="mini" 
                  slot="reference"
                ></el-button>
              </el-popconfirm> -->
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div v-show="!isShowTable">
        <el-form label-width="80px" :model="attrInfo">
          <el-form-item label="属性名">
            <el-input
              placeholder="请输入属性名"
              v-model="attrInfo.attrName"
              style="width: 500px"
            ></el-input>
          </el-form-item>
        </el-form>
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="addAttrValue"
          :disabled="!attrInfo.attrName"
        >
          添加属性值
        </el-button>
        <el-button @click="isShowTable = true">取消</el-button>

        <el-table
          style="width: 100%; margin: 20px 0px"
          border
          :data="attrInfo.attrValueList"
        >
          <el-table-column type="index" label="序号" width="80" align="center">
          </el-table-column>
          <el-table-column prop="prop" label="属性值名称" width="width">
            <template slot-scope="{ row, $index }">
              <el-input
                v-model="row.valueName"
                placeholder="请输入属性名称"
                size="mini"
                v-if="row.flag"
                @blur="toLook(row)"
                @keyup.native.enter="toLook(row)"
                :ref="$index"
              ></el-input>
              <span v-else @click="toEdit(row, $index)" style="display: block">
                {{ row.valueName }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="prop" label="操作" width="width">
            <template slot-scope="{ row, $index }">
              <el-popconfirm
                :title="`你确定删除 ${row.valueName} 吗？`"
                @onConfirm="deleteAttrValue($index)"
              >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  slot="reference"
                  :ref="$index"
                ></el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-button
          type="primary"
          @click="addOrUpdateAttr"
          :disabled="attrInfo.attrValueList.length < 1"
          >保存
        </el-button>
        <el-button @click="isShowTable = true">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
//引入lodash中的神烤被
import cloneDeep from "lodash/cloneDeep";

export default {
  name: "Attr",
  data() {
    return {
      attrList: [],
      category1Id: "",
      category2Id: "",
      category3Id: "",
      isShowTable: true,
      attrInfo: {
        attrName: "",
        attrValueList: [],
        categoryId: 0,
        categoryLevel: 3,
      },
    };
  },
  methods: {
    getCategoryId({ categoryId, level }) {
      if (level == 1) {
        this.category1Id = categoryId;
        this.category2Id = "";
        this.category3Id = "";

      } else if (level == 2) {
        this.category2Id = categoryId;
        this.category3Id = "";

      } else {
        this.category3Id = categoryId;
        //发请求
        this.getAttrList();
      }
    },
    //发请求
    async getAttrList() {
      const { category1Id, category2Id, category3Id } = this;
      let result = await this.$API.attr.reqAttrList(
        category1Id,
        category2Id,
        category3Id
      );
      // console.log(result);
      if (result.code == 200) {
        this.attrList = result.data;
      }
    },
    //添加属性值
    addAttrValue() {
      this.attrInfo.attrValueList.push({
        attrId: this.attrInfo.id,
        valueName: "",
        flag: true,
      });
      //当点击添加，自动聚焦
      // this.$nextTick(() => {
      //   this.$refs[this.attrInfo.attrValueList.length - 1].focus();
      // });
    },
    //添加属性
    addAttr() {
      this.isShowTable = false;
      this.attrInfo = {
        attrName: "",
        attrValueList: [],
        categoryId: this.category3Id,
        categoryLevel: 3,
      };
    },
    //修改摸个属性
    updateAttr(row) {
      // alert(123)
      this.isShowTable = false;
      // 将选中的选项赋值给attrInfo
      this.attrInfo = cloneDeep(row);
      //在修改某一个属性时，将相应的属性元素添加flag标记
      this.attrInfo.attrValueList.forEach((item) => {
        this.$set(item, "flag", false);
      });
    },
    toLook(row) {
      //row是当前用户添加的最新的属性
      if (row.valueName.trim() == "") {
        this.$message("输入不能为空");
        return;
      }
      let isRepat = this.attrInfo.attrValueList.some((item) => {
        if (row !== item) {
          return row.valueName == item.valueName;
        }
      });
      if (isRepat) return;
      row.flag = false;
    },
    //点击自动聚焦
    toEdit(row, index) {
      row.flag = true;
      //点击span的时候切换input为编辑模式
      //对于浏览器，页面重绘与重排需要消耗时间，点击span的时候不能立马获取到input
      this.$nextTick(() => {
        this.$refs[index].focus();
      });
    },
    //删除属性值
    deleteAttrValue(index) {
      this.attrInfo.attrValueList.splice(index, 1);
    },
    //保存按钮，添加或修改属性
    addOrUpdateAttr() {
      // console.log(111);
      this.attrInfo.attrValueList = this.attrInfo.attrValueList.filter(
        (item) => {
          //过滤掉属性值不是空的
          if (item.valueName != "") {
            //提交的数据中不应该有flag字段
            //删除flag属性
            delete item.flag;
            return true;
          }
        }
      );
      //发请求
      // console.log(this.$API);
      this.$API.attr.reqAddOrUpdateAttr(this.attrInfo).then((res) => {
        this.isShowTable = true;
        //提示消息
        this.$message({
          type: "success",
          message: "保存成功",
        });
        //再次发请求获取品台属性进行展示
        this.getAttrList();
      });

      // try {
      //   //发请求
      //   let res = await this.$API.attr.reqAddOrUpdateAttr(this.attrInfo)

      //   this.isShowTable = true
      //   this.$message({
      //     type:'success',
      //     message:'保存成功'
      //   })
      //   this.getAttrList()
      // } catch (error) {
      //   this.$message('保存失败')
      // }
    },
  },
};
</script>

<style>
</style>
